//
//  AddressViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/25.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

enum AddressListType: Int {
    case province = 0
    case city     = 1
    case area     = 2
}

class AddressViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        judgeType()
    }
    
    var chooseClosure: ((_ addrInfoModel: AddressInfoModel) -> Void)?
    
    @IBOutlet private weak var contentView: UIView! {
        didSet {
            contentView.layer.cornerRadius = 10
            contentView.layer.masksToBounds = true
        }
    }

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(AddressViewCell.nibForCell(),
                               forCellReuseIdentifier: AddressViewCell.reuseIdentifier())
        }
    }
    
    @IBOutlet private weak var provinceBtn: UIButton!
    
    @IBOutlet private weak var cityBtn: UIButton!
    
    @IBOutlet private weak var areaBtn: UIButton!
    
    @IBOutlet private weak var closeBtn: UIButton!
    
    @IBOutlet private weak var line: UIView! {
        didSet {
            line.backgroundColor = .mainColor
        }
    }
    
    @IBOutlet private weak var activityView: UIActivityIndicatorView!
    
    private var buttonArray: [UIButton] = []
    
    private var addressInfo = AddressInfoModel()
    
    private var listType = AddressListType.province
    
    private var allArray: [[AddressModel]] = [[], [], []] {
        didSet {
            tableView.reloadData()
            let list = allArray[listType.rawValue]
            for (index, model) in list.enumerated(){
                if model.name == showName {
                    showIndex = index
                    tableView.selectRow(at: IndexPath(row: index, section: 0), animated: true, scrollPosition: .top)
                } else {
                    tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
                }
            }
        }
    }
    
    var showName = ""
    var showIndex = 0
}

extension AddressViewController {
    @IBAction private func closeAction(_ sender: UIButton) {
        view.backgroundColor = .clear
        dismiss(animated: true)
    }
    
    @IBAction private func buttonClickedAction(_ sender: UIButton) {
        switch sender.tag {
        case 0:
            showName = addressInfo.provinceName
            listType = .province
            setupButtonTitle()
            getProvinceList()
        case 1:
            showName = addressInfo.cityName
            listType = .city
            setupButtonTitle()
            getCityList(proviceId: addressInfo.provinceId)
        case 2:
            showName = addressInfo.areaName
            listType = .area
            setupButtonTitle()
            getAreaList(cityId: addressInfo.cityId)
        default: break
        }
    }
}

// MARK: - Data
private extension AddressViewController {
    func getProvinceList() {
        self.activityView.startAnimating()
        AddressModel.getProvinceList(success: { models in
            self.activityView.stopAnimating()
            self.allArray[self.listType.rawValue] = models
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func getCityList(proviceId: String) {
        self.activityView.startAnimating()
        AddressModel.getCityList(provinceId: proviceId, success: { models in
            self.activityView.stopAnimating()
            self.allArray[self.listType.rawValue] = models
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func getAreaList(cityId: String) {
        self.activityView.startAnimating()
        AddressModel.getAreaList(cityId: cityId, success: { models in
            self.activityView.stopAnimating()
            self.allArray[self.listType.rawValue] = models
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
}

private extension AddressViewController {
    func judgeType() {
        buttonArray = [provinceBtn, cityBtn, areaBtn]
        resetButtonTitle()
        
        if addressInfo.cityName != "" {
            showName = addressInfo.areaName
            listType = .area
            setupButtonTitle()
            getAreaList(cityId: addressInfo.cityId)
        } else if addressInfo.provinceName != "" {
            listType = .city
            setupButtonTitle()
            getCityList(proviceId: addressInfo.provinceId)
        } else {
            listType = .province
            setupButtonTitle()
            getProvinceList()
        }
    }
    
    func resetButtonTitle() {
        self.provinceBtn.setTitle(addressInfo.provinceName, for: .normal)
        self.cityBtn.setTitle(addressInfo.cityName, for: .normal)
        self.areaBtn.setTitle(addressInfo.areaName, for: .normal)
    }
    
    func setupButtonTitle(){
        buttonArray.forEach {
            $0.setTitleColor(UIColor.textDark, for: .normal)
        }
        
        var button: UIButton!
        switch listType {
        case .province:
            self.provinceBtn.setTitleColor(UIColor.mainColor, for: .normal)
            self.provinceBtn.setTitle(getReminderTitle(addressInfo.provinceName) , for: .normal)
            button = self.provinceBtn
        case .city:
            self.cityBtn.setTitleColor(UIColor.mainColor, for: .normal)
            self.cityBtn.setTitle(getReminderTitle(addressInfo.cityName) , for: .normal)
            button = self.cityBtn
        case .area:
            self.areaBtn.setTitleColor(UIColor.mainColor, for: .normal)
            self.areaBtn.setTitle(getReminderTitle(addressInfo.areaName) , for: .normal)
            button = self.areaBtn
        }
        
        UIView.animate(withDuration: 0.25) {
            self.line.left = button.left
        }
    }
    
    func getReminderTitle(_ title: String) -> String {
        return title == "" ? "请选择" : title
    }
    
    func didChoose(_ type: AddressListType, model: AddressModel) {
        switch type {
        case .province:
            addressInfo.provinceName = model.name
            addressInfo.provinceId = model.id
            
            addressInfo.cityName = ""
            addressInfo.cityId = ""
            addressInfo.areaName = ""
            addressInfo.areaId = ""
            
            listType = .city
            resetButtonTitle()
            setupButtonTitle()
            getCityList(proviceId: model.id)
            
        case .city:
            addressInfo.cityName = model.name
            addressInfo.cityId = model.id
            
            addressInfo.areaName = ""
            addressInfo.areaId = ""
            
            listType = .area
            resetButtonTitle()
            setupButtonTitle()
            getAreaList(cityId: model.id)
            
        case .area:
            addressInfo.areaName = model.name
            addressInfo.areaId = model.id
            
            resetButtonTitle()
            setupButtonTitle()
            
            view.backgroundColor = .clear
            chooseClosure?(addressInfo)
            dismiss(animated: true)
        }
    }
}

extension AddressViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allArray.isEmpty ? 0 : allArray[listType.rawValue].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AddressViewCell.reuseIdentifier(),
                                                 for: indexPath) as! AddressViewCell
        
        let model = allArray[listType.rawValue][indexPath.row]
        
        cell.titleLabel.text = model.name
        
        if cell.titleLabel.text == showName {
            cell.titleLabel.textColor = .mainColor
        } else {
            cell.titleLabel.textColor = .textDark
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
}

extension AddressViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard !allArray[listType.rawValue].isEmpty else { return }
        let model = allArray[listType.rawValue][indexPath.row]
        didChoose(listType, model: model)
    }
}
